package com.example.net.interceptor;


import com.example.net.utils.NetWorkUtil;

import java.io.IOException;

import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 创建者     ZCL
 * 创建时间   2018/3/22 14:07
 * 描述	      ${TODO}
 * <p>
 * 更新者     $Author$
 * 更新时间   $Date$
 * 更新描述   ${TODO}
 */

public class CacheNoNetIntercepter implements Interceptor{


    //创建一个拦截器
    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();
        if (!NetWorkUtil.isNetworkAvailable()) {
            //无网络 从缓存中取
            Request requestCache = request.newBuilder()
                    .cacheControl(CacheControl.FORCE_CACHE)//ASIAskServerIfModifiedWhenStaleCachePolicy
                    .build();
            return chain.proceed(requestCache);
        } else {
            //有网络  存入缓存 设置缓存时间为一天
            int maxtime = 60 * 60 * 24;
            //获取旧的response
            Response response = chain.proceed(request);

            //获取新的response
            Response promaResponse = response.newBuilder()
                    .header("Cache-Control", "public, only-if-cached, max-stale=" + maxtime)
                    .removeHeader("Progma")
                    .build();

            return promaResponse;
        }
    }
}
